<?php
/**
 * Static Class for Data Sync
 * @author Aimon
 * */
class Sync {
	
	/*
	public static function order() {
	 	$fields = ['id', 'COMPANY_id', 'TERM_id', 'EMPLOYEE_id', 'WALLET_id', 'peso', 'points', 'tax', '`status`', 'payment_method', 'topup', 'delivery_fee', '`comment`', 'created_at', 'updated_at', 'archived'];
		self::render('order', $fields);
	}
	*/

	/**
	 * Sync All Orders From Client Databases to Main Databases
	 * @author Aimon
	 * */
	public static function fromClientToMainOrder() {
		$pdo = DB::connection()->getPdo();

		$companies = Config::get('app.companies');

		$prefix = Config::get('app.prefix');

		foreach($companies as $company) {
			$company = $prefix . $company;
			$pdo->query("UPDATE `" . $prefix . "main`.`order` 
						INNER JOIN `" . $company . "`.`order` ON `" . $prefix . "main`.`order`.`id` = `" . $company . "`.`order`.`id`
						SET `" . $prefix . "main`.`order`.`created_at`	= `" . $company . "`.`order`.`created_at`,
							`" . $prefix . "main`.`order`.`updated_at`	= `" . $company . "`.`order`.`updated_at`,
							`" . $prefix . "main`.`order`.`status`		= `" . $company . "`.`order`.`status`,
							`" . $prefix . "main`.`order`.`archived`	= `" . $company . "`.`order`.`archived`");
		}

		$fields = ['id', 'TERM_id', 'ORDER_id', 'MANUFACTURER_id', 'CATEGORY_id', 'PRODUCT_id', 'SIZE_id', 'ORDER_PRODUCT_OPTION_id', 'WALLET_id', '`name`', 'model', 'benstore_price', 'quantity', '`status`', 'delivery_fee_peso', 'delivery_fee_points', 'dr_number', 'dr_date', 'peso', 'tax', 'points', 'topup', 'created_at', 'updated_at', 'archived'];
		self::replace('order_product', $fields);

		$fields = ['id', 'TERM_ID', 'ORDER_id', 'SET_id', 'set_name', 'delivery_method', 'address', 'unit', 'street', 'barangay', 'city', 'zip_code', 'mobile', 'zone_fee', 'zone_name'];
		self::replace('order_to_set', $fields);
	}

	/**
	 * Replace Function on getting the table
	 * @author Aimon
	 * */
	public static function replace($table, $fields, $condition='') {
		$pdo = DB::connection()->getPdo();

		$companies = Config::get('app.companies');

		$prefix = Config::get('app.prefix');

		$fields = "`" . implode("`,`", $fields) . "`";

		foreach($companies as $company) {
			$company = $prefix . $company;
			$pdo->query("REPLACE INTO `" . $prefix . "main`.`" . $table . "` ( " . str_replace('``', '`',$fields) . " ) SELECT " . str_replace('``', '`',$fields)  . " FROM `" . $company. "`.`" . $table . "` " . ( $condition ? ' WHERE ' . $condition : '') );
		}
	}
}